<template>
  <div class="container">
    <i
      @click="changeMode"
      :style="{ right: mode == 'fold' ? '5px' : '-17px', 'z-index': 6 }"
      :class="icon"
    ></i>
    <div
      id="resizableDiv"
      :style="{ width: divWidth + 'px', transition: transitionStyle }"
      class="content"
      :class="mode"
      @mousedown="startResize"
    >
      <div
        id="resizeHandle"
        style="
          position: absolute;
          top: 0;
          right: 0;
          width: 5px;
          height: 100%;
          cursor: ew-resize;
        "
      ></div>
      <slot></slot>
    </div>
  </div>
</template>

<script>
const trans = {
  unfold: "fold",
  fold: "unfold",
};
export default {
  name: "CollapseAside",
  data() {
    return {
      mode: "unfold",
      transitionStyle: "",
      isResizing: false,
      startX: 0,
      startWidth: 0,
      divWidth: 0,
      divWidthCopy: 200,
    };
  },
  computed: {
    icon() {
      return `el-icon-s-${this.mode}`;
    },
  },
  methods: {
    changeMode() {
      if (this.isResizing) {
        return;
      }
      this.transitionStyle = "width 0.5s ease-in-out";

      if (this.mode == "unfold") {
        this.divWidth = this.divWidthCopy;
      } else {
        // 设置备份以及0
        this.divWidthCopy = this.divWidth;
        this.divWidth = 0;
      }
      this.mode = trans[this.mode];
      setTimeout(() => {
        this.transitionStyle = "";
      }, 500);
    },
    startResize(event) {
      event.preventDefault();
      
      this.isResizing = true;
      this.startX = event.clientX;
      this.startWidth = this.divWidth;
      document.documentElement.addEventListener("mousemove", this.resizeDiv);
      document.documentElement.addEventListener("mouseup", this.stopResizeDiv);
    },
    resizeDiv(event) {
      if (this.isResizing) {
        this.divWidth = this.startWidth + (event.clientX - this.startX);
      }
    },
    stopResizeDiv() {
      this.isResizing = false;
      document.documentElement.removeEventListener("mousemove", this.resizeDiv);
      document.documentElement.removeEventListener(
        "mouseup",
        this.stopResizeDiv
      );
    },
  },
};
</script>

<style lang='less' scoped>
@width: 24px;
#resizeHandle {
  position: absolute;
  top: 0;
  right: 0;
  width: 5px;
  height: 100%;
  cursor: w-resize;
}
.container {
  width: fit-content; /* 设置初始宽度 */
  height: calc(100% - 2px);
  border: 1px solid #ccc;
  //   overflow: hidden;
  position: fixed;
  top: 60px;
  left: 0;
  z-index: 5;
  background-color: #fff;
  i {
    position: absolute;
    top: calc(50% - 20px);
    transform: scale(1.5);
  }

  .content {
    height: calc(100% - 20px);
    // padding: 10px;
    overflow: hidden;
  }
}

.unfold {
  // 折叠
  width: 0;
  padding: 0 !important;
  right: -@width;
}
.fold {
  //展开
  width: 300px;
  right: 0;
}
</style>